package com.lakala.sh.bps.bpsmerchant.client.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;

import java.util.*;

/**
 * @author: peijian
 * @date: 2019/12/2 16:07
 */
public class SignUtil {

    /**
     * 将reqData中的请求参数，以字母顺序正排序，然后拼接成 参数=值|参数=值|参数=值|secretKey 的方式拼接成字符串，然后对该字符串做md5加签
     * 将加签后获取的md5值，赋予公共请求参数中的sign
     * @param json
     * @param secretKey
     * @return
     * @throws Exception
     */
    public static String md5Sign(String json, String secretKey) throws Exception {
        StringBuffer content = new StringBuffer("");

        Map map = JSON.parseObject(json, SortedMap.class, Feature.IgnoreNotMatch, Feature.OrderedField);
        Set keys = map.keySet();
        Iterator it = keys.iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            String value = Objects.toString(map.get(key), "");
            content.append(key).append("=").append(value).append("|");
        }
        content.append(secretKey);
        String signStr = MD5Util.getMD5(content.toString());
        return signStr;
    }
}
